package thread;

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;

    private long time;

    public MyTimerTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        //此处需要的是小堆
        return (int)(this.time - o.time);
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<MyTimerTask>();

    private Object locker = new Object();

    public MyTimer() {
        //创建线程，执行任务
        Thread t = new Thread(() -> {
            try {
                while(true) {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            //如果不写成wait会在短时间进行多次循环，循环多次都是在频繁加锁，造成线程饿死问题，此时就可以使用wait解决
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        //判断当前时间是否达到指定的时间
                        if(System.currentTimeMillis() >= task.getTime()) {
                            //执行任务
                            task.run();
                            //执行完的任务删除队列
                            queue.poll();
                        }else {
                            //没到达时间，先不执行任务，但是如果此处也不写wait而是用continue进行处理，也会一直不断地进行加锁和解锁的操作，此时则使用固定等待时间的wait减少加锁和解锁的开销
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        }
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t.start();
    }

    public void schedule(Runnable runnable,long delay) {
        synchronized(locker) {
            MyTimerTask task = new MyTimerTask(runnable,delay);
            queue.add(task);
            locker.notify();
        }
    }
}


public class Demo32 {
}
